<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" label-width="68px" size="mini">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="销售单号" prop="saleOdd">
            <el-input v-model="queryParams.saleOdd" clearable placeholder="请输入" @keyup.enter.native="handleQuery"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="客户名称" prop="customerName">
            <el-input v-model="queryParams.customerName" clearable placeholder="请输入" @keyup.enter.native="handleQuery"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="销售状态" prop="saleStatus">
            <el-select v-model="queryParams.saleStatus" clearable placeholder="请选择">
              <el-option v-for="dict in dict.type.erp_procure_batch" :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="销售日期" prop="saleTime">
            <el-date-picker v-model="dateRange" end-placeholder="结束日期" range-separator="-" start-placeholder="开始日期" type="daterange" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label-width="10px">
            <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['erp:ErpSale:add']" icon="el-icon-plus" plain size="mini" type="primary" @click="handleAdd">新增销售单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['erp:ErpSale:export']" icon="el-icon-download" plain size="mini" type="warning" @click="handleExport">列表导出</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button v-hasPermi="['erp:ErpSale:import']" icon="el-icon-upload2" plain size="mini" type="primary"
                   @click="handleImport">批量导入
        </el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ErpSaleList" row-key="saleId" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="50" align="center" :reserve-selection="true"/>
      <el-table-column align="center" label="销售单号" sortable prop="saleOdd" />
      <el-table-column align="center" label="客户名称" prop="customerName" />
      <el-table-column align="center" label="销售状态" prop="saleStatus" sortable width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.saleStatus == 0" type="info">草稿</el-tag>
          <el-tag v-if="scope.row.saleStatus == 1" type="primary">待审批</el-tag>
          <el-tag v-if="scope.row.saleStatus == 2" type="success">已通过</el-tag>
          <el-tag v-if="scope.row.saleStatus == 3" type="danger">被驳回</el-tag>
          <el-tag v-if="scope.row.saleStatus == 4" type="success">已完成</el-tag>
          <el-tooltip v-if="scope.row.saleStatus == 3" effect="light" placement="bottom">
            <div slot="content">
              {{ scope.row.rejectReason }}
            </div>
            <i class="el-icon-warning-outline" style="margin-left: 5px; color: red"></i>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column align="center" label="物流状态" prop="logisticsStauts" sortable width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.erp_logistics_stauts" :value="scope.row.logisticsStauts"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="销售/下单人" prop="nickName"  width="120"/>
      <el-table-column align="center" label="销售/下单日期" prop="saleTime" sortable width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.saleTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="联系电话" prop="phonenumber"  width="180"/>
      <el-table-column align="center" label="销售金额" prop="payAmount" sortable width="120">
        <template slot-scope="scope">
          <span>{{ formattedNumber(scope.row.payAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="销售利润" sortable width="120">
        <template slot-scope="scope">
          <span>{{ formattedNumber(scope.row.rateMoney) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="审核人" prop="approveName"  width="120"/>
      <el-table-column align="center" label="审核时间" prop="approveTime" sortable width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建人" prop="createName"  width="120"/>
      <el-table-column align="center" label="备注" prop="remark"/>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button v-if="[0, 3].includes(scope.row.saleStatus)" v-hasPermi="['erp:ErpSale:edit']" size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-if="[1].includes(scope.row.saleStatus)" v-hasPermi="['erp:ErpSale:audit']" size="mini" type="text" @click="handleViewOrAudit(scope.row, 2)">审核</el-button>
          <el-button v-if="[2].includes(scope.row.saleStatus)" v-hasPermi="['erp:ErpSale:edit']" size="mini" type="text" @click="handleLogistics(scope.row)">更改物流状态</el-button>
          <el-button v-hasPermi="['erp:ErpSale:view']" size="mini" type="text" @click="handleViewOrAudit(scope.row, 1)">查看</el-button>
          <el-button v-if="[0, 1].includes(scope.row.saleStatus)" v-hasPermi="['erp:ErpSale:remove']" size="mini" type="text" @click="handleUpdateFlag(scope.row)">关闭</el-button>
          <el-button v-if="[2, 4].includes(scope.row.saleStatus)" v-hasPermi="['erp:ErpSale:print']" size="mini" type="text" @click="handleViewOrAudit(scope.row, 3)">打印</el-button>
          <el-button v-if="[2, 4].includes(scope.row.saleStatus)" size="mini" type="text" @click="handleExportDetails(scope.row)" v-hasPermi="['erp:ErpSale:export']">导出</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total" @pagination="getList"/>

    <!-- 审核or预览 -->
    <el-dialog :title="viewAuditTitle" :visible.sync="isAuditOrViewOpen" append-to-body width="80%">
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <div id="printXSForm">
          <div class="title">湖南三才环境科技有限公司（销售单）</div>
          <div class="head-print">
            <div>销售单号：{{ form.saleOdd }}</div>
            <div>销售日期：{{ parseTime(form.saleTime, "{y}年{m}月{d}日") }}</div>
            <div>销售人：{{ form.nickName }}</div>
            <div>审核人：{{  form.approveName }}</div>
          </div>
          <div class="head-print">
            <div>客户名称：{{ form.customerName }}</div>
            <div>联系人：{{ form.linkman }}</div>
            <div>联系电话：{{ form.linkmanPhone }}</div>
            <div>客户地址：{{ form.address }}</div>
          </div>
          <right-toolbar :columns="columns" :refresh="false" :search="false" class="no-print"></right-toolbar>
          <table class="table_print">
            <tr>
              <th v-if="columns[0].visible" width="80px">序号</th>
              <th v-if="columns[1].visible">商品编号</th>
              <th v-if="columns[2].visible">商品名称</th>
              <th v-if="columns[3].visible">商品类别</th>
              <th v-if="columns[4].visible">规格</th>
              <th v-if="columns[5].visible">单位</th>
              <th v-if="columns[6].visible">单位关系</th>
              <th v-if="columns[7].visible">成本价</th>
              <th v-if="columns[9].visible">销售数量</th>
              <th v-if="columns[8].visible">销售单价</th>
              <th v-if="columns[10].visible">销售金额</th>
              <th v-if="columns[11].visible">销售利润</th>
              <th v-if="columns[12].visible">备注</th>
            </tr>
            <tr v-for="(item,index) in form.detailsList" :key="index">
              <td v-if="columns[0].visible">{{index + 1}}</td>
              <td v-if="columns[1].visible">{{item.commodityNo}}</td>
              <td v-if="columns[2].visible">{{item.commodityName1}}</td>
              <td v-if="columns[3].visible">{{item.commodityType}}</td>
              <td v-if="columns[4].visible">{{item.commoditySpec}}</td>
              <td v-if="columns[5].visible">{{item.unitName1}}</td>
              <td v-if="columns[6].visible">{{item.unitRelationship}}</td>
              <td v-if="columns[7].visible">{{formattedNumber(item.unitResult * item.costPrice)}}</td>
              <td v-if="columns[9].visible">{{item.saleNumber }}</td>
              <td v-if="columns[8].visible">{{formattedNumber(item.salePrice)}}</td>
              <td v-if="columns[10].visible">{{formattedNumber(item.saleMoney) }}</td>
              <td v-if="columns[11].visible">{{formattedNumber(item.rateMoney) }}</td>
              <td v-if="columns[12].visible">{{item.detailsRemark }}</td>
            </tr>
          </table>
          <div class="bottom-print">
            <div>物流费用：{{ formattedNumber(form.logisticsCost) }} / {{ form.logisticsMethod == 1 ? "按重量" : "按体积" }}</div>
            <div>其他费用：{{ formattedNumber(form.otherCost) }} /
              {{ form.otherMethod == 1 ? "按重量" : "按体积" }}</div>
            <div>合计数量：{{ form.sumNumber }}</div>
            <div>销售金额：{{  formattedNumber(form.payAmount) }}</div>
            <!-- <div v-if="columns[11].visible">销售利润：{{  formattedNumber(form.rateMoney) }}</div> -->
          </div>
          <div class="single-line-print">制单人：{{ $store.getters.nickName}}</div>
          <div class="single-line-print">单据备注：{{ form.remark }}</div><br/>
          <div class="bottom-print">
            <div>出库：</div>
            <div>送货：</div>
            <div>收货：</div>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="type == 2" type="primary" @click="handleAuditOptions(2)">通过</el-button>
        <el-button v-if="type == 2" type="primary" @click="handleAuditOptions(3)">驳回</el-button>
        <el-button v-if="type == 3" v-print="'#printXSForm'" type="primary">打印</el-button>
        <el-button @click="isAuditOrViewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :visible.sync="isUpdateLogisticsOpen" append-to-body title="更改物流状态" width="400px">
      <el-form :model="saleObj">
        <el-select v-model="saleObj.logisticsStauts" clearable placeholder="请选择" style="width: 90%">
          <el-option v-for="dict in dict.type.erp_logistics_stauts" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isUpdateLogisticsOpen = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdateLogisticsSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  auditErpSale,
  getErpSale,
  listErpSale,
  updateErpSale,
  logistics
} from "@/api/erp/ErpSale";
import {formattedNumber} from "@/utils/ruoyi";

export default {
  name: "ErpSale",
  dicts: ["erp_procure_batch", "erp_logistics_stauts"],
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 多选ids
      ids: [],
      // 销售单表格数据
      ErpSaleList: [],
      // 是否显示弹出层
      open: false,
      viewAuditTitle: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        saleOdd: null,
        customerName: null,
        saleTime: null,
        saleStatus: null,
      },
      // 审核 预览弹框
      isAuditOrViewOpen: false,
      // 选中销售单
      saleObj: {
        saleId: null,
        saleStatus: null,
      },
      form: {},
      // 更改物流状态
      isUpdateLogisticsOpen: false,
      // 打印列
      columns: [
        { key: 0, label: `序号`, visible: true },
        { key: 1, label: `商品编号`, visible: true },
        { key: 2, label: `商品名称`, visible: true },
        { key: 3, label: `商品类别`, visible: true },
        { key: 4, label: `规格`, visible: true },
        { key: 5, label: `单位`, visible: true },
        { key: 6, label: `单位关系`, visible: true },
        { key: 7, label: `成本价`, visible: true },
        { key: 8, label: `销售单价`, visible: true },
        { key: 9, label: `销售数量`, visible: true },
        { key: 10, label: `销售金额`, visible: true },
        { key: 11, label: `销售利润`, visible: true },
        { key: 12, label: `备注`, visible: true },
      ],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    formattedNumber,
    /** 查询销售单列表 */
    getList() {
      this.loading = true;
      listErpSale(this.queryParams).then((response) => {
        this.ErpSaleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.saleId)
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push("/ErpSale/add-sale/erpSale/0");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push("/ErpSale/add-sale/erpSale/" + row.saleId);
    },
    /** 关闭 */
    handleUpdateFlag(row) {
      row.flag = "N";
      this.$modal
        .confirm('是否确认关闭采销售单号为"' + row.saleOdd + '"的数据项？')
        .then(function () {
          return updateErpSale(row);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        })
        .catch(() => {});
    },
    // 查看详情 / 审核
    handleViewOrAudit(row, type) {
      getErpSale(row.saleId).then((res) => {
        this.form = res.data;
        this.form.sumNumber = 0;
        this.form.detailsList.forEach((i) => {
          this.form.sumNumber += i.saleNumber;
          // 销售金额
          i.saleMoney = i.saleNumber * i.salePrice * i.saleRate;
          // 折后金额
          i.rateMoney = i.saleMoney - (i.saleNumber * (i.unitResult * i.costPrice));
        });
        this.viewAuditTitle = "销售单：" + this.form.saleOdd;
        this.type = type;
        this.isAuditOrViewOpen = true;
      });
    },
    handleAuditOptions(type) {
      this.form.saleStatus = type;
      if (type == 3) {
        this.$prompt("", "驳回原因", {
          center: true,
          inputType: "textarea",
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }).then(({ value }) => {
          this.form.rejectReason = value;
          this.handleAudit();
        });
      } else {
        this.handleAudit();
      }
    },
    // 审核
    handleAudit() {
      auditErpSale({
        saleId: this.form.saleId,
        saleStatus: this.form.saleStatus,
        rejectReason: this.form.rejectReason,
      }).then((res) => {
        this.$modal.msgSuccess("操作成功");
        this.isAuditOrViewOpen = false;
        this.getList();
      });
    },
    /** 更改物流状态 */
    handleLogistics(row) {
      this.saleObj = row;
      this.isUpdateLogisticsOpen = true;
    },
    /** 更改物流状态提交 */
    handleUpdateLogisticsSubmit() {
      logistics(this.saleObj).then((response) => {
        this.$modal.msgSuccess("操作成功");
        this.isUpdateLogisticsOpen = false;
        this.getList();
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "erp/ErpSale/export",
        {
          ...this.queryParams,
          exportIds: this.ids?.join(',')
        },
        `销售单_${new Date().getTime()}.xlsx`
      );
    },
     // 导出
     handleExportDetails(row){
      this.download('erp/ErpSale/exportDetails/' + row.saleId, {}, `销售单_${row.saleOdd}.xlsx`)
    }
  },
};
</script>
<style scoped>
.title {
  padding: 10px;
  text-align: center;
  font-size: 32px;
  font-weight: 500;
}

.oddInfo {
  font-size: 16px;
}

.remark {
  padding-top: 10px;
  padding-bottom: 10px;
}

table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}
</style>
